from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4BuildingInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4BuildingInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class SpecialBuildingInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()

	def isProductionTraitDefined(self, iSpecialBuilding):
		objSpecialBuildingInfo = gc.getSpecialBuildingInfo(iSpecialBuilding)
		
		for iI in range (gc.getNumTraitInfos()):
			if(objSpecialBuildingInfo.getProductionTraits(iI) != 0):
				return true				
		return false


	def printSpecialBuilding(self, iSpecialBuilding):
		objSpecialBuildingInfo = gc.getSpecialBuildingInfo(iSpecialBuilding)

		szText = ""
		
		szText = appendString(szText,"		<SpecialBuildingInfo>")
		
		szText = appendString(szText,"			<Type>%s</Type>" %(objSpecialBuildingInfo.getType()))

		szText = appendString(szText,"			<Description>%s</Description>" %(objSpecialBuildingInfo.getTextKey()))

		if(objSpecialBuildingInfo.getObsoleteTech() != -1):
			szText = appendString(szText,"			<ObsoleteTech>%s</ObsoleteTech>" %(gc.getTechInfo(objSpecialBuildingInfo.getObsoleteTech()).getType()))
		else:
			szText = appendString(szText,"			<ObsoleteTech>NONE</ObsoleteTech>")

		if(objSpecialBuildingInfo.getTechPrereq() != -1):
			szText = appendString(szText,"			<TechPrereq>%s</TechPrereq>" %(gc.getTechInfo(objSpecialBuildingInfo.getTechPrereq()).getType()))
		else:
			szText = appendString(szText,"			<TechPrereq>NONE</TechPrereq>")

		szText = appendString(szText,"			<bValid>%s</bValid>" %(boolToInt(objSpecialBuildingInfo.isValid())))

		if(self.isProductionTraitDefined(iSpecialBuilding)):
			szText = appendString(szText,"			<ProductionTraits>")
			for iI in range (gc.getNumTraitInfos()):
				if(objSpecialBuildingInfo.getProductionTraits(iI) > 0):
					szText = appendString(szText,"				<ProductionTrait>")
					szText = appendString(szText,"					<ProductionTraitType>%s</ProductionTraitType>" %(gc.getTraitInfo(iI).getType()))
					szText = appendString(szText,"					<iProductionTrait>%s</iProductionTrait>" %(objSpecialBuildingInfo.getProductionTraits(iI)))
					szText = appendString(szText,"				</ProductionTrait>")
			szText = appendString(szText,"			</ProductionTraits>")
		else:
			szText = appendString(szText,"			<ProductionTraits/>")

		szText = appendString(szText,"			<Button>%s</Button>" %(objSpecialBuildingInfo.getButton()))

		szText = appendString(szText,"		</SpecialBuildingInfo>")
			
		return szText

						
	def printSpecialBuildings(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\Buildings" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4SpecialBuildingInfos.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Special Building -->")
		szText = appendString(szText,"<Civ4SpecialBuildingInfos xmlns=\"x-schema:CIV4BuildingsSchema.xml\">")
		szText = appendString(szText,"	<SpecialBuildingInfos>")
				
		for iSpecialBuilding in range(gc.getNumSpecialBuildingInfos()):

			if(gc.getSpecialBuildingInfo(iSpecialBuilding).isDeleted()):
				continue

			szText = appendString(szText,self.printSpecialBuilding(iSpecialBuilding))
			
						
		szText = appendString(szText,"	</SpecialBuildingInfos>")
		szText = appendString(szText,"</Civ4SpecialBuildingInfos>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\Buildings")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\Buildings\CIV4SpecialBuildingInfos.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
			
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

